<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bus:jqtCpInfo:add']">新增企业</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['bus:jqtCpInfo:remove']">删除新增企业</el-button>
          </el-col>
          <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="jqtCpInfoList" @selection-change="handleSelectionChange"
          :preserve-expanded-content="preserveExpanded"
                style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="唯一ID" align="center" prop="id" v-if="false" />
        <el-table-column label="获客链接" width="100" type="expand">
          <template #default="props">
            <el-table :data="props.row.cpLinksVoList" border>
              <el-table-column/>
              <el-table-column label="链接名称" prop="linkName" />
              <el-table-column label="链接地址" prop="linkUrl" show-overflow-tooltip/>
              <el-table-column label="状态" prop="status">
                <template #default="scope">
                  <dict-tag :options="sys_normal_disable" :value="scope.row.status"></dict-tag>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" prop="createTime" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="danger" @click="handleDeleteCpLinks(scope.row)" v-hasPermi="['bus:jqtCpLinks:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column label="企业名称" align="center" prop="corpName" />
        <el-table-column label="企业ID" align="center" prop="corpId" show-overflow-tooltip/>
        <el-table-column label="应用ID" align="center" prop="suiteId" show-overflow-tooltip/>
        <el-table-column label="授权时间" prop="createTime" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
          <template #default="scope">
            <el-button link type="primary" @click="handleAdd" v-hasPermi="['bus:jqtCpInfo:add']">添加获客链接</el-button>
            <el-button link type="primary" @click="editRemarkData(scope.row)" v-hasPermi="['bus:jqtCpInfo:edit']">备注</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['bus:jqtCpInfo:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改企业信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="350px" append-to-body @close="getList">
      <el-alert
        v-if="!quotaLoading"
        class="mb-2"
        :title="`当前剩余额度：${userQuota.customerAssistantCount ?? 0} 个获客助手`"
        :type="userQuota.customerAssistantCount > 0 ? 'success' : 'warning'"
        show-icon
        :closable="false"
      />

      <div v-if="qrCode">
        <el-image style="width: 300px; height: 300px" :src="qrCode" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="JqtCpInfo" lang="ts">
import {
  listJqtCpInfo,
  getJqtCpInfo,
  delJqtCpInfo,
  addJqtCpInfo,
  updateJqtCpInfo,
  editRemark, addCpInfoCode
} from '@/api/bus/jqtCpInfo';
import { JqtCpInfoVO, JqtCpInfoQuery, JqtCpInfoForm } from '@/api/bus/jqtCpInfo/types';
import { delJqtCpLinks } from '@/api/bus/jqtCpLinks';
import { JqtCpLinksVO } from '@/api/bus/jqtCpLinks/types';
import { getUserXcxQuota } from '@/api/bus/jqtXcxInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

// ✅ 用户额度信息
const userQuota = ref<Record<string, number>>({})
const quotaLoading = ref(false)


const jqtCpInfoList = ref<JqtCpInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
//在折叠后是否在DOM中保留展开行内容
const preserveExpanded = ref(false)
const queryFormRef = ref<ElFormInstance>();
const jqtCpInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: JqtCpInfoForm = {
  id: undefined,
  remark: undefined,
  userId: undefined,
  suiteId: undefined,
  corpId: undefined,
  corpName: undefined,
  corpFullName: undefined,
  authUserId: undefined,
  authOpenUserid: undefined,
  authName: undefined,
  authAvatar: undefined,
  permanentCode: undefined,
  subjectType: undefined,
  corpWxqrcode: undefined,
  verifiedEndTime: undefined,
  status: undefined
}
const data = reactive<PageData<JqtCpInfoForm, JqtCpInfoQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    suiteId: undefined,
    corpId: undefined,
    corpName: undefined,
    corpFullName: undefined,
    authUserId: undefined,
    authOpenUserid: undefined,
    authName: undefined,
    authAvatar: undefined,
    permanentCode: undefined,
    subjectType: undefined,
    corpWxqrcode: undefined,
    verifiedEndTime: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户id不能为空", trigger: "blur" }
    ],
    suiteId: [
      { required: true, message: "应用id不能为空", trigger: "blur" }
    ],
    corpId: [
      { required: true, message: "企业ID不能为空", trigger: "blur" }
    ],
    corpName: [
      { required: true, message: "企业名称不能为空", trigger: "blur" }
    ],
    corpFullName: [
      { required: true, message: "企业全称不能为空", trigger: "blur" }
    ],
    authUserId: [
      { required: true, message: "授权管理员用户id不能为空", trigger: "blur" }
    ],
    authOpenUserid: [
      { required: true, message: "授权管理员开放用户id不能为空", trigger: "blur" }
    ],
    authName: [
      { required: true, message: "授权管理员名称不能为空", trigger: "blur" }
    ],
    authAvatar: [
      { required: true, message: "授权管理员头像url不能为空", trigger: "blur" }
    ],
    permanentCode: [
      { required: true, message: "企业微信永久授权码不能为空", trigger: "blur" }
    ],
    subjectType: [
      { required: true, message: "企业类型，1. 企业; 2. 政府以及事业单位; 3. 其他组织, 4.团队号不能为空", trigger: "change" }
    ],
    corpWxqrcode: [
      { required: true, message: "授权企业在微信插件不能为空", trigger: "blur" }
    ],
    verifiedEndTime: [
      { required: true, message: "认证到期时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态(0.正常 1.停用)不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企业信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listJqtCpInfo(queryParams.value);
  jqtCpInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  jqtCpInfoFormRef.value?.resetFields();
  qrCode.value = '';
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: JqtCpInfoVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

//企业微信授权二维码
const qrCode = ref<string>('');
/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加企业微信";

  quotaLoading.value = true;
  try {
    const res = await getUserXcxQuota();
    userQuota.value = res.data || {};
  } finally {
    quotaLoading.value = false;
  }

  // 如果额度为0，提示并禁用二维码加载
  if ((userQuota.value.customerAssistantCount ?? 0) <= 0) {
    proxy?.$modal.msgWarning("当前剩余额度为 0，请购买套餐后再添加企业微信！");
    qrCode.value = '';
    return;
  }

  const data = await addCpInfoCode();
  qrCode.value = data.data;
};

/** 提交按钮 */
const submitForm = () => {
  jqtCpInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateJqtCpInfo(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addJqtCpInfo(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: JqtCpInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除企业信息编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delJqtCpInfo(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('bus/jqtCpInfo/export', {
    ...queryParams.value
  }, `jqtCpInfo_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});

/** 编辑备注 */
const editRemarkData = async (row?: JqtCpInfoVO) => {
  const _ids = row?.id || ids.value;
  ElMessageBox.prompt('修改企业备注', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  })
    .then(async ({ value }) => {
      await editRemark({
        id: row?.id,
        remark: value
      });
      proxy?.$modal.msgSuccess("编辑成功");
      row.remark = value;
    })
    .catch(() => {
    })
}

/** 删除链接按钮操作 */
const handleDeleteCpLinks = async (row?: JqtCpLinksVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除链接名称为"' + row.linkName + '"的数据项？').finally(() => loading.value = false);
  await delJqtCpLinks(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}
</script>
